package com.item.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.JSONUtils;
import com.base.util.StringUtil;
import com.item.dao.model.School;
import com.item.dao.model.SchoolExample;
import com.item.exception.JSONRepUtils;
import com.item.service.SchoolService;

@Controller
public class SchoolController {
	@Autowired
	private SchoolService schoolService;
	
	@RequestMapping("/listSchool")
	@ResponseBody
	public String list(Page param, Integer isNotPage, Integer isM) throws Exception{
		Object objForSer = null;
		SchoolExample example = new SchoolExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);

		example.setOrderByClause("code ASC");
		List<School> list = schoolService.selectByExample(example);
		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		}
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showlistSchool")
	public String list() {
		return "school/schoolList";
	}
	
	@RequestMapping("/toEditSchool")
	public String toEdit()throws Exception{
		return "school/schoolEdit";
	}
	
	@RequestMapping(value="/saveSchool",method=RequestMethod.POST)
	@ResponseBody
	public String save(School school, Integer isTop, HttpSession session)throws Exception{		
		try{
			if(StringUtil.isEmpty(school.getId())){
				school.setCode(schoolService.getLeastCode());
				
				school.setCreateTime(new Date());
				schoolService.insertSelective(school);
			} else {
				school.setModifyTime(new Date());
				schoolService.updateByPrimaryKeySelective(school);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdSchool")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		School n = schoolService.selectByPrimaryKey(id);

		return JSONUtils.serialize(n);
	}
	
	@RequestMapping("/delSchool")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			schoolService.deleteByPrimaryKey(ids[i]);
		}
		return "{\"success\":true}";
	}
	
	
}

